#include "camera.h"
#include "memory.h"
#include <stdint.h>
#include "render.h"
#include "widget/widget.h"

typedef struct{
    int x,y,w,h;
    uint8_t *gram_output;
}camera_t;

camera_t camera;


void camera_init(may_screen_t* screen)
{
    camera.w = screen->obj.w;
    camera.h = screen->obj.h;
    camera.gram_output = memory_alloc(screen->obj.w * (screen->obj.h/8));
}

void carmera_mask_gram(uint8_t sx, uint8_t sy)
{
    render_gram_desc_t gram_desc = render_get_gram();
    
    // 检查输入坐标是否超出范围
    if (sx >= gram_desc.w || sy >= gram_desc.h) {
        return; 
    }

    camera.x = 0;
    camera.y = 0;

    for (int y = sy; y < camera.h + sy; y += 8) {
        camera.x = 0;
        for (int x = sx; x < camera.w + sx; x++) {
            int y_high = y / 8;
            int y_low = y % 8;

            int byte_index_high = (y_high * gram_desc.w + x) / 8;
            uint8_t orig_data_high = gram_desc.gui_ram[byte_index_high];
            uint8_t output_data = orig_data_high;

            if (y_low) {
                int byte_index_low = ((y_high + 1) * gram_desc.w + x) / 8;
                uint8_t orig_data_low = gram_desc.gui_ram[byte_index_low];
                uint8_t mask = 0xFF << (8 - y_low);
                orig_data_high &= mask;
                orig_data_low &= ~mask;

                output_data = orig_data_high | orig_data_low;
            }

            camera.gram_output[camera.y / 8 * camera.w + camera.x] = output_data;
            camera.x++;
        }

        camera.y += 8;
    }
}

void camera_output_to_screen(void)
{
    ;
}
